from rest_framework.views import APIView
from rest_framework.response import Response
from django_redis import get_redis_connection
import random
from . import constants
from meiduo_mall.utils.ytx_sdk.ytx_sdk.sendSMS import CCP
from celery_tasks.sms.tasks import send_sms


class SmsAPIView(APIView):
    def get(self, request, mobile):
        '''
        发送短信验证码
        :param request: 请求对象
        :param mobile: 手机号
        :return: 是否发送成功
        '''
        # 说明：包含有效时间的设置，向redis中保存数据
        # 连接redis，参数是cache中的键
        redis_cli = get_redis_connection('sms')
        # 1.验证60秒内是否向此手机号发过短信，如果发过则返回
        if redis_cli.get('sms_flag_' + mobile):
            return Response({'message': '请稍候再向此手机号发短信'})
        # 2.如果未改过，则继续执行
        # 2.1生成随机6位的验证码
        sms_code = random.randint(100000, 999999)
        # 2.2保存验证码、发送标记
        redis_pipeline = redis_cli.pipeline()
        redis_pipeline.setex('sms_' + mobile, constants.SMS_EXPIRES, sms_code)
        redis_pipeline.setex('sms_flag_' + mobile, constants.SMS_FLAG_EXPIRES, 1)
        # 一次性将命令加到redis中执行
        redis_pipeline.execute()
        # 2.3发送
        # print(sms_code)
        # CCP.sendTemplateSMS(mobile, sms_code, constants.SMS_EXPIRES / 60, 1)
        # 调用任务
        send_sms.delay(mobile, sms_code, constants.SMS_EXPIRES / 60, 1)

        return Response({'message': 'OK'})
